﻿using GodSoft.Code;
using GodSoft.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace GodSoft.Common
{
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        GodSoftContext _context = new GodSoftContext();
        //定义一个基类的UserInfo对象
        //public UserInfo CurrentUserInfo { get; set; }
        public int currentUserID { get; set; }
        /// <summary>
        /// 重写基类在Action之前执行的方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            #region -----校验用户是否登录进入网站的-----


            if (filterContext.HttpContext.Session["currentUserID"] != null)
            {
                currentUserID = Int32.Parse(filterContext.HttpContext.Session["currentUserID"].ToString());
            }
            else
            {
                filterContext.Result=new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Index" }, { "Controller", "Login" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });
            }
            #endregion

            #region -------检验用户是否有访问此地址的权利----
            //拿到当前请求的URL地址
            string requestUrl = filterContext.HttpContext.Request.Path;
            //拿到当前请求的类型
            string requestType = filterContext.HttpContext.Request.RequestType.ToLower().Equals("get") ? "HttpGet" : "HttpPost";

            //判断是否在权限表中
            if (_context.ActionInfoes.Any(i => i.RequestUrl == requestUrl && i.RequestHttpType == requestType))
            {
                //如果当前访问的页面在权限表中，查看用户是否拥有权限
                //没有权限,返回登录页面
                if (!PermissionAccess.UserHasPermission(currentUserID, requestUrl, requestType))
                {
                    filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Index" }, { "Controller", "Login" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });

                 }
                else//有权限，执行该页面
                {
                    return;
                }
            }
            else//不在权限表中的，是公共访问资源，任何用户可以操作
            {
                return;
            }
            #endregion

        }
   

}
  
}